package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.APUserRealNameMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRealNameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ApUserRealNameServiceImpl extends ServiceImpl<APUserRealNameMapper, ApUserRealname> implements ApUserRealNameService {

    /**
     * 分页条件查询实名认证列表
     *
     * @param dto 封装数据对象
     * @return 返回页面数据结果
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //判断参数是否为空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "查询失败!");
        }
        //创建分页对象
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        //创建查询条件构建器
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        //添加条件
        wrapper.eq(dto.getStatus() != null, ApUserRealname::getStatus, dto.getStatus());

        //进行分页
        IPage<ApUserRealname> result = this.page(page, wrapper);
        //返回页面数据对象
        return new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal(), result.getRecords());

    }


    @Autowired
    ApUserMapper apUserMapper;

    /**
     * 实名认证审核
     *
     * @param dto
     * @param status
     * @return
     */
    @Override
    //全局事务注解
//    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //参数校验 判断id 是否为空
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数错误!");
        }
        //根据id查询实名认证信息
        ApUserRealname userRealname = this.getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getUserId, dto.getId()));
        //判断当前对象是否为null
        if (userRealname == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "实名认证信息不存在");
        }
        //检查状态 是否 为1
        if (!AdminConstants.WAIT_AUTH.equals(userRealname.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "实名认证非待审核状态");
        }
        //根据实名认证的userId查询关联是否存在
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId, userRealname.getUserId()));
        //判断是否为null
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "实名认证信息关联的用户不存在");
        }
        //3 更新认证用户信息
        //更新状态码
        userRealname.setStatus(status);
        //更新修改时间
        userRealname.setUpdatedTime(new Date());
        //判断理由是否为空
        if (StringUtils.isNotBlank(dto.getMsg())) {
            //设置驳回理由
            userRealname.setReason(dto.getMsg());
        }
        //修改实名认证信息
        updateById(userRealname);
        //判断审核状态为2  直接 return
        if (AdminConstants.FAIL_AUTH.equals(status)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "审核已经被驳回");
        }
        //判断审核状态为9 继续
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //开通自媒体
            WmUser wmUser = createWmUser(apUser);
            //创建作者信息
            createApAuthor(wmUser);
        }
        //返回ok信息
        return ResponseResult.okResult();
    }


    @Autowired
    ArticleFeign articleFeign;

    /**
     * 创建作者账户
     *
     * @param wmUser
     */
    private void createApAuthor(WmUser wmUser) {
        //1 检查是否成功调用 根据id查询用户信息是否存在
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(wmUser.getApUserId());
        //判断状态码
        if (result.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, result.getErrorMessage());
        }
        //2. 检查作者信息是否已经存在 从查询的结果中获取对象
        ApAuthor apAuthor = result.getData();
        if (apAuthor != null) {
            //不为null说明已经存在,返回错误信息
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "当前作者已存在!");
        }
        apAuthor = new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        //用户id
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(new Date());
        //自媒体id
        apAuthor.setWmUserId(wmUser.getId());

        //3. 添加作者信息
        ResponseResult responseResult = articleFeign.save(apAuthor);
        //4. 结果失败，抛出异常
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, responseResult.getErrorMessage());
        }
    }


    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 创建自媒体账户
     *
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //根据名字查找自媒体账户是否存在
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        //判断状态码是否等于0
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, result.getErrorMessage());
        }
        //拿出数据
        WmUser wmUser = result.getData();
        if (wmUser != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "自媒体用户信息已存在");
        }
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
        wmUser.setApUserId(apUser.getId());
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());

        //调用保存方法
        ResponseResult<WmUser> responseResult = wemediaFeign.save(wmUser);
        //判断状态码是否为0
        if (responseResult.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, responseResult.getErrorMessage());
        }
        //返回保存的对象
        return responseResult.getData();
    }


}
